package com.sg.common.empty.core;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.sg.common.empty.entity.Myinput;
import com.sg.common.empty.entity.PerfProperty;
import com.sg.common.empty.entity.Property;
import com.sg.common.empty.json.SecList;
import com.sg.common.empty.service.CfgService;
import com.sg.common.http.HttpHelper;
import com.sg.common.utils.CollUtil;
import com.sg.common.utils.Constant;
import com.sg.common.utils.ReUtils;
import com.sg.common.utils.StrUtil;

public class EpUtil {
	private static Logger logger = LoggerFactory.getLogger(EpUtil.class);

	// ConditionPartSqlForReplace
	public static String CPSFR = "@ConditionPart";

	/**
	 * 在创建可执行sql时,把配置文件中的 CPSFR 进行替换
	 * 
	 * @param sql
	 * @param condition
	 * @return
	 */
	public static String replaceCondition(String sql, String condition) {
		return StringUtils.replace(sql, CPSFR, condition);
	}

	public static Object createBlankMv(String body) {
		ModelAndView mv = new ModelAndView("/jsp/blank");
		mv.addObject("body", body);
		return mv;
	}

	public static String findMyCode(HttpServletRequest request) {
		String memberCode = "";
		String yornsso = Constant.get("yornsso");
		if (yornsso.equals("yes")) {
			Map<String, String> mip = new HashMap<String, String>();
			mip.put("clientIp", request.getRemoteAddr());
			long s = System.currentTimeMillis();
			JSONObject httpRes = HttpHelper.httpPost(Constant.get("checkin"),
					mip);
			long e = System.currentTimeMillis();
			logger.info("login lasts : {}", e - s);
			if (httpRes != null
					&& StringUtils.equals(httpRes.getString("errmsg"), "ok")) {
				memberCode = httpRes.getString("loginid");
			}
		} else {
			memberCode = (String) request.getSession().getAttribute(
					Constant.SESSION_MEMBER_CODE);
		}
		return memberCode;
	}

	public static List<String> findRemoteRoles(HttpServletRequest request,
			String memberCode) {
		List<String> roleCodes = new ArrayList<String>();
		Map<String, String> mip = new HashMap<String, String>();
		mip.put("code", memberCode);
		mip.put("sName", Constant.get("sName"));
		long s = System.currentTimeMillis();
		JSONObject httpRes = HttpHelper.httpPost(Constant.get("remoteRoles"),
				mip);
		long e = System.currentTimeMillis();
		logger.info("login lasts : {}", e - s);
		if (httpRes != null
				&& StringUtils.equals(httpRes.getString("errmsg"), "ok")) {
			String roleCodesStr = httpRes.getString("roleCodes");
			if (StringUtils.isNotEmpty(roleCodesStr)) {
				String[] split = StringUtils.split(roleCodesStr, ":");
				roleCodes = java.util.Arrays.asList(split);
			}
		} else{
			roleCodes = null;
		}
		return roleCodes;
	}

	/**
	 * 如果是流程bean，则增加流程历史查看
	 * 
	 * @param sls
	 * @param bean
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static SecList[] flowAttachment(Object bean)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		String isFlow = ReUtils.getStr(bean, "isFlow");
		if (StringUtils.equals(isFlow, "1")) {
			SecList history = new SecList();
			history.setParam("_proInsId");
			history.setParamValue("proInsId");
			history.setTitle("流程历史查看");
			history.setUrl("acti/common/history");
			// if(sls==null){
			SecList[] res = new SecList[1];
			res[0] = history;
			return res;
			// }else{
			// List<SecList> asList = Arrays.asList(sls);
			// List<SecList> list = new ArrayList<SecList>(asList);
			// list.add(history);
			// return (SecList[]) list.toArray(new
			// SecList[list.size()]);//toArray()会返回object【】，然后在强制转换过程中出错
			// }
		}
		// return sls;
		return null;
	}

	/**
	 * //对于含外键类，需要把外键的x.id，改成x={id=??}的Map形式，并放入需保存的map（beanMap）
	 * 
	 * @param beanMap
	 * @param pps
	 */
	public static void changePointFormatForDb(Map<String, Object> beanMap) {
		Map<String, Map<String, Object>> saveMap = new HashMap<String, Map<String, Object>>();
		Set<String> keySet = beanMap.keySet();
		for (String key : keySet) {
			if (StringUtils.endsWith(key, ".id")) {
				Map<String, Object> nm = new HashMap<String, Object>();
				String[] keyPoint = StringUtils.split(key, ".");
				nm.put(keyPoint[1], beanMap.get(key));
				saveMap.put(keyPoint[0], nm);
			}
		}
		beanMap.putAll(saveMap);
	}

	/**
	 * 通过ref（例子propertys），将request中参数（propertys[x].yy）集成到一个list中
	 * 
	 * @param request
	 * @param ref
	 * @param refClass
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static List<Object> smObjs(HttpServletRequest request, String ref,
			String refClass) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException,
			InvocationTargetException, NoSuchMethodException {
		List<Object> ol = new ArrayList<Object>();
		@SuppressWarnings("unchecked")
		Map<String, String[]> parameterMap = request.getParameterMap();
		Set<String> keySet = parameterMap.keySet();
		List<String> keys = new ArrayList<String>();// 只包含muti参数
		int max = 0;// list提交了几行
		for (String key : keySet) {
			if (!StringUtils.contains(key, "_") && key.startsWith(ref + "[")) {
				keys.add(key);
				String ind = (String) key.subSequence(key.indexOf("[") + 1,
						key.indexOf("]"));
				if (Integer.valueOf(ind) > max) {
					max = Integer.valueOf(ind);
				}
			}
		}
		if (refClass.contains(".dym.")) {
			while (max >= 0) {
				Map<String, Object> o = new HashMap<String, Object>();
				// Object o = Class.forName(refClass).newInstance();
				o.put(Constant.BEAN_TYPE, refClass);
				ol.add(o);// 根据最大提交行，创建muti参数list
				max--;
			}
		} else {
			while (max >= 0) {
				Object o = Class.forName(refClass).newInstance();
				ol.add(o);// 根据最大提交行，创建muti参数list
				max--;
			}
		}
		for (String key : keys) {
			String indx = (String) key.substring(key.indexOf("[") + 1,
					key.indexOf("]"));
			Object o = ol.get(Integer.valueOf(indx));
			String pro = key.substring(key.indexOf("]") + 2);
			String value = (parameterMap.get(key))[0];
			if (refClass.contains(".dym.")) {
				if (StringUtils.isNotEmpty(value))
					ReUtils.set(o, pro, value);
			} else {
				putPropertyValue(value, o, pro);
			}

		}
		return ol;
	}

	// public static Object showSpecialButtons(Perf perf, HttpServletRequest
	// request) {
	// @SuppressWarnings("unchecked")
	// List<Permission> specialPermission = (List<Permission>) request
	// .getAttribute("specialPermission");
	//
	// if (specialPermission != null) {
	// StringBuilder showSpecial = JspUtil3.showSpecial(perf.getId(),
	// specialPermission);
	// return commonView(showSpecial, new StringBuilder(), request);
	// } else {
	// return commonView(new StringBuilder("not defined yet!"),
	// new StringBuilder(), request);
	// }
	// }

	public static ModelAndView commonView(StringBuilder body, StringBuilder js,
			HttpServletRequest request) {
		ModelAndView res = new ModelAndView("/jsp/common");
		citeMv(res, request);
		res.addObject("jsHtml", js.toString());
		res.addObject("bodyHtml", body.toString());
		return res;
	}

	public static void citeMv(ModelAndView res, HttpServletRequest request) {
		String citeParam = request.getParameter("_cite");
		if (StringUtils.isEmpty(citeParam) || "null".equals(citeParam)) {
			res.addObject("cite", cite(request));
		}
	}

	public static String cite(HttpServletRequest request) {
		StringBuilder res = new StringBuilder();
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath()
				+ "/";
		res.append(" <base href='").append(basePath).append("'>");
		res.append("<title></title>");
		res.append("<meta http-equiv='pragma' content='no-cache'>	<meta http-equiv='cache-control' content='no-cache'>	<meta http-equiv='expires' content='0'>	<meta http-equiv='keywords' content='keyword1,keyword2,keyword3'>	<meta http-equiv='description' content='This is my page'>");
		// res.append("<link rel='stylesheet' type='text/css' href='kalendae/css/kalendae.css'>	<link rel='stylesheet' type='text/css' href='css/table.css' />	<link rel='stylesheet' type='text/css' href='css/link.css' />	<link rel='stylesheet' type='text/css'		href='easyui-1.3.2/themes/icon.css' />	<link rel='stylesheet' type='text/css'		href='easyui-1.3.2/themes/metro/easyui.css' />	<link rel='stylesheet' type='text/css' href='easyui-1.3.2/demo/demo.css'>	<link href='bootstrap/bootstrap/css/bootstrap.min.css' rel='stylesheet'		media='screen'>	<link href='bootstrap/assets/styles.css' rel='stylesheet' media='screen'>	<style type='text/css'>	* {		font-size: 15px;	}		.row-fluid [class *='span']:first-child {		margin-left: 2.12766%;	}	</style>	<style media=print>	.noprint {		display: none;	}	</style>		<script type='text/javascript' src='kalendae/js/kalendae.js'></script>	<script type='text/javascript' src='easyui-1.3.2/jquery-1.8.0.min.js'></script>	<script type='text/javascript' src='easyui-1.3.2/jquery.easyui.min.js'></script>	<script type='text/javascript'		src='easyui-1.3.2/locale/easyui-lang-zh_CN.js'></script>	<script type='text/javascript' src='easyui-1.3.2/easyloader.js'></script>	<script type='text/javascript' src='js/layer.js'></script>");
		res.append("<link rel='stylesheet' type='text/css' href='kalendae/css/kalendae.css'>	"
				+ "<link rel='stylesheet' type='text/css' href='css/table.css' />	"
				+ "<link rel='stylesheet' type='text/css' href='css/link.css' />	"
				+ "<link rel='stylesheet' type='text/css'		href='jquery-easyui-1.5.2/themes/icon.css' />	"
				+ "<link rel='stylesheet' type='text/css'		href='jquery-easyui-1.5.2/themes/metro/easyui.css' />	"
				+ "<link rel='stylesheet' type='text/css' href='jquery-easyui-1.5.2/demo/demo.css'>	"
				+ "<link href='bootstrap/bootstrap/css/bootstrap.min.css' rel='stylesheet'		media='screen'>	"
				+ "<link href='bootstrap/assets/styles.css' rel='stylesheet' media='screen'>	"
				+ "<style type='text/css'>	* {		font-size: 15px;	}		.row-fluid [class *='span']:first-child {		margin-left: 2.12766%;	}	</style>	<style media=print>	.noprint {		display: none;	}	</style>		"
				+ "<script type='text/javascript' src='kalendae/js/kalendae.js'></script>		"
				+ "<script type='text/javascript' src='jquery-easyui-1.5.2/jquery.min.js'></script>	"
				+ "<script type='text/javascript' src='jquery-easyui-1.5.2/jquery.easyui.min.js'></script>	"
				+ "<script type='text/javascript'		src='jquery-easyui-1.5.2/locale/easyui-lang-zh_CN.js'></script>"
				+ "<script type='text/javascript' src='jquery-easyui-1.5.2/easyloader.js'></script>	"
				+ "<script type='text/javascript' src='js/layer.js'></script>");
		return res.toString();
	}

	/**
	 * 把对象bean的key属性赋值，值为value
	 * 
	 * @param value
	 * @param bean
	 * @param key
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 * @throws InstantiationException
	 */
	public static void putPropertyValue(String value, Object bean, String key)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException, InstantiationException {
		String[] ss = StringUtils.split(key, ".");
		Class<?> typeOne = ReUtils.typeOneLev(bean, key);
		if (StringUtils.isNotEmpty(value)) {
			if (ss.length == 1) {
				if (typeOne.equals(int.class)) {
					PropertyUtils
							.setProperty(bean, key, Integer.valueOf(value));
				} else {
					PropertyUtils.setProperty(bean, key, value);
				}
			} else if (ss.length > 1) {
				Object tmp = ReUtils.get(bean, ss[0]);
				if (tmp == null)
					tmp = typeOne.newInstance();
				Class<?> typeTwo = ReUtils.typeOneLev(tmp, ss[1]);
				if (typeTwo != null) {
					if (typeTwo.equals(int.class)) {
						PropertyUtils.setProperty(tmp, ss[1],
								Integer.valueOf(value));
						PropertyUtils.setProperty(bean, ss[0], tmp);
					} else {
						PropertyUtils.setProperty(tmp, ss[1], value);
						PropertyUtils.setProperty(bean, ss[0], tmp);
					}
				}
			}

		}
	}

	/**
	 * e,r,t => e,r,t '' => descr
	 * 
	 * @param forDescr
	 * @return
	 */
	public static List<String> findDescrPropertyByFd(String forDescr) {
		List<String> descrs = new ArrayList<String>();

		if (StringUtils.isNotEmpty(forDescr)) {// 有描述字段，则将得到字段列表
			descrs = StrUtil.split(forDescr);
		} else {
			descrs.add(Constant.DESCR);
		}
		return descrs;
	}

	/**
	 * 为url加额外的参数值，所以有一个判断，是否该url正带着参数
	 * 
	 * @param url
	 * @param param
	 * @return
	 */
	public static String addParam(String url, String param) {
		String res = url;
		if (!url.contains("?")) {
			res += "?" + param;
		} else {
			res += "&" + param;
		}
		return res;
	}

	// public static List<PerfProperty> findPpsBySearch(String psid) {
	// List<PerfProperty> res = new ArrayList<PerfProperty>();
	// for (PerfProperty pp : Constant.PPS) {
	// Perf perf = pp.getPerf();
	// String esh = pp.getEsh();
	// if (perf.getId().equals(psid)
	// && ("2".equals(esh) || "0".equals(esh) || "3".equals(esh))) {
	// if ("0".equals(esh))
	// pp.setEsh("3");
	// res.add(pp);
	// }
	// }
	// return res;
	// }

	// public static List<PerfProperty> findEditAndHidePps(Perf perf) {
	// List<PerfProperty> pps = new ArrayList<PerfProperty>();
	// pps.addAll(findPpsById(perf.getId(), "2"));// 提取需要编辑\hide的PP
	// pps.addAll(findPpsById(perf.getId(), "0"));
	// return pps;
	// }

	// public static List<PerfProperty> findPpsById(String perfid) {
	// List<PerfProperty> res = new ArrayList<PerfProperty>();
	// for (PerfProperty pp : Constant.PPS) {
	// // System.out.println(pp.getId());
	// if (pp.getPerf().getId().equals(perfid)) {
	// res.add(pp);
	// }
	// }
	// return res;
	// }

	// public static List<PerfProperty> findPpsById(String perfid, String esh) {
	// List<PerfProperty> res = new ArrayList<PerfProperty>();
	// for (PerfProperty pp : Constant.PPS) {
	// // System.out.println(pp.getId());
	// if (pp.getPerf().getId().equals(perfid)
	// && esh.equals(pp.getEsh())) {
	// res.add(pp);
	// }
	// }
	// return res;
	// }

	/**
	 * 找到对应perf下的隐藏的PP 并且不包含在ppl中
	 * 
	 * @param ppl
	 * @param pid
	 * @return
	 */
	// public static List<PerfProperty> findHidePp(List<PerfProperty> ppl,
	// String pid) {
	// List<PerfProperty> res = new ArrayList<PerfProperty>();
	// for (PerfProperty pp : Constant.PPS) {
	// Perf perf = pp.getPerf();
	// if (perf.getId().equals(pid) && "0".equals(pp.getEsh())
	// && !ppl.contains(pp)) {
	// res.add(pp);
	// }
	// }
	// return res;
	// }

	public static PerfProperty findPpById(String ppid) {
		for (PerfProperty pp : Constant.PPS) {
			if (pp.getId().equals(ppid)) {
				return pp;
			}
		}
		return null;
	}

	// public static PerfProperty findPpByPn(String property, String pid) {
	// for (PerfProperty pp : Constant.PPS) {
	// if (pp.getPerf().getId().equals(pid)
	// && pp.getProperty().getProperty().equals(property)) {
	// return pp;
	// }
	// }
	// return null;
	// }

	// public static List<PerfProperty> findPpsByList(String psid) {
	// List<PerfProperty> res = new ArrayList<PerfProperty>();
	// for (PerfProperty pp : Constant.PPS) {
	// Perf perf = pp.getPerf();
	// if (perf.getId().equals(psid)
	// && ("1".equals(pp.getEsh()) || "2".equals(pp
	// .getEsh()))) {
	// res.add(pp);
	// }
	// }
	// return res;
	// }

	public static Property getPropByName(List<Property> pl, String name) {
		for (Property pp : pl) {
			String propertyName = pp.getProperty();
			if (StringUtils.equals(propertyName, name)) {
				return pp;
			}
		}
		return null;
	}

	public static List<Object> transParams(CfgService service,
			List<String> params) {
		List<Object> sqlParams = new ArrayList<Object>();
		if (params != null) {
			for (String f : params) {
				sqlParams.add(FilterVal.init(f, service).get().toString());
			}
		}
		return sqlParams;
	}

	public static String buildCondition(List<PerfProperty> searchPl,
			HttpServletRequest request) {
		String beanValue;
		StringBuilder conditon = new StringBuilder();
		if (searchPl != null) {
			for (PerfProperty pp : searchPl) {
				Property property = pp.getProperty();
				String field = property.getProperty();
				beanValue = request.getParameter(field);
				if (StringUtils.isNotEmpty(beanValue)) {
					Myinput input = JspUtil3.propertyMyinput(pp);
					if (input != null) {
						String inputType = input.getType();
						// TODO 待扩展搜索模式
						if (StringUtils.equals(inputType, "text")
								|| StringUtils.equals(inputType, "textarea")) {
							conditon.append(" and " + field + " like '%"
									+ beanValue + "%'");
						} else {
							conditon.append(" and " + field + "='" + beanValue
									+ "'");
						}
					}
				}
			}
		}
		return conditon.toString();
	}

	public static String buildConditionSel(List<String> searchs,
			HttpServletRequest request) {
		StringBuilder conditon = new StringBuilder();
		if (CollUtil.isNotEmpty(searchs)) {
			for (String s : searchs) {
				conditon.append(" and " + s + "='" + request.getParameter(s)
						+ "' ");
			}
		}
		return conditon.toString();
	}
}
